
package com.tuni.birthdaymoney.service.util.security;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import com.tuni.birthdaymoney.persistence.entity.User;
import com.tuni.birthdaymoney.service.UserService;

@Component
public class BirthdayMoneyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;
    @Autowired
    private HashProvider hashProvider;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        String email = authentication.getName();
  
        User user = userService.getUserByEmail(email);
    	
        try {
        	
            if (user != null
                    && hashProvider.validatePassword(authentication.getCredentials().toString(), user.getHashPass(), user.getSalt())) {
                return new UsernamePasswordAuthenticationToken(email, authentication.getCredentials(), authorities);
            }
        } catch (NoSuchAlgorithmException e) {
            // TODO: Log this things!
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO: Log this things!
            e.printStackTrace();
        }
        throw new BadCredentialsException("Invalid Credentials.");
    }

    public boolean supports(Class<? extends Object> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
